<template>
  <div>
    <div class="box" ref="box">
      <div class="bwiii">{{ btname }}</div>
      <canvas
        id="myCanvas"
        :width="hbwidth"
        :height="hbheight"
        class="myCanvasd"
      ></canvas>
    </div>

    <!-- 添加标记的输入框 -->

    <!-- 编辑标记的面板 -->
  </div>
</template>

<script>
  export default {
    props: {
      permarkers: {
        default: [],
      },
    },
    data() {
      return {
        imgsrc: [],
        btname: '',
        canBiaoZhu: false,
        pointColor: '#ff8484',
        pointSize: 15,
        imgScale: 0.8,
        zoomStep: 0.1,
        canvas: null,
        ctx: null,
        img: null,
        imgWidth: 300,
        hbheight: '',
        hbwidth: '',
        imgHeight: 730,
        currentText: '',
        currentMarker: null,
        showLinesAndText: true,
        isDragging: false,
        startDragX: 0,
        startDragY: 0,
        imgOffsetX: 0,
        imgOffsetY: 0,
        isSpacePressed: false,
        hoveredMarker: null,
        editingMarker: false,
        editPanelX: 0,
        editPanelY: 0,
        addflag: false,
        imgScales: '',
        dcomid: 1,
        isHovering: false,
      };
    },
    watch: {
      permarkers: {
        handler(i) {
          if (i.length > 0) {
            console.log('接收到数据', i);
            this.$nextTick(() => {
              this.saveMarkers();
            });
          }
        },
        immediate: true,
        deep: true,
      },
    },
    methods: {
      cancelEditing() {
        this.editingMarker = false;
        this.draw();
      },
      checkHover(x, y) {
        // console.log('当前坐标', x, y);
        const { permarkers, pointSize, imgScale, imgOffsetX, imgOffsetY } =
          this;
        // console.log('鼠标带的', permarkers)
        // 查找当前标记点
        const targetElement = permarkers.find(
          (item) => item.dcomid == this.dcomid
        );
        if (targetElement) {
          this.hoveredMarker = targetElement.bsdata.find((marker) => {
            // xinde
            const canvas = this.canvas;
            const ctx = this.ctx;
            const img = this.img;

            ctx.clearRect(0, 0, canvas.width, canvas.height);
            // // 计算缩放尺寸
            // const aspectRatio = this.img.naturalWidth / this.img.naturalHeight;
            // const canvasAspectRatio = canvas.width / canvas.height;

            // // 最大宽度和高度
            // const maxWidth = canvas.width * 0.9; // 设置为画布宽度的90%
            // const maxHeight = canvas.height * 0.9; // 设置为画布高度的90%

            // if (canvasAspectRatio > aspectRatio) {
            //   this.imgScales = Math.min(maxHeight / this.img.naturalHeight, 1);
            // } else {
            //   this.imgScales = Math.min(maxWidth / this.img.naturalWidth, 1);
            // }
            // console.log('比例', this.imgScale);
            // const scaledWidth = this.img.naturalWidth * this.imgScales;
            // const scaledHeight = this.img.naturalHeight * this.imgScales;

            // Calculate scaled image dimensions
            const scaledWidth = this.imgWidth * this.imgScale;
            const scaledHeight = this.imgHeight * this.imgScale;

            // Calculate image offset on the canvas
            const xOffset = (canvas.width - scaledWidth) / 2;
            const yOffset = (canvas.height - scaledHeight) / 2;
            const markerX = marker.x * imgScale + xOffset;
            const markerY = marker.y * imgScale + yOffset;

            const isHoveringMarker =
              Math.hypot(x - markerX, y - markerY) < (pointSize / 2) * imgScale;

            if (isHoveringMarker) return true;

            const isMarkerLeft =
              markerX < (this.canvas.width - 50) / 2 + 50 / 2;
            const lineLength = 100 * imgScale;
            const lineEndX = isMarkerLeft
              ? markerX - lineLength
              : markerX + lineLength;
            const lineEndY = markerY;

            const distanceToLine =
              Math.abs(
                (lineEndY - markerY) * x -
                  (lineEndX - markerX) * y +
                  lineEndX * markerY -
                  lineEndY * markerX
              ) / Math.hypot(lineEndY - markerY, lineEndX - markerX);

            if (distanceToLine < 10 * imgScale) {
              const textWidth = this.ctx.measureText(marker.text).width;
              const textHeight = 14 * imgScale;
              const textPadding = 10 * imgScale;
              const textX =
                lineEndX +
                (isMarkerLeft ? -textWidth - textPadding : textPadding);
              const textY = lineEndY + 5 * imgScale;

              return (
                x >= textX &&
                x <= textX + textWidth &&
                y >= textY - textHeight &&
                y <= textY
              );
            }

            return false;
          });
          if (this.hoveredMarker != null) {
            this.isHovering = true;
            this.btname = this.hoveredMarker.text;
          } else {
            this.isHovering = false;
            this.btname = '请选择一个部位';
          }
        }
      },
      handleMouseMove(e) {
        // console.log('检测到移动鼠标', e)

        this.canvas.style.cursor = this.isHovering ? 'pointer' : 'default';
        const canvasX = e.offsetX;
        const canvasY = e.offsetY;
        this.checkHover(canvasX, canvasY); // 其他鼠标移动逻辑（例如检查悬停）
        this.draw(); // 绘制更新
      },
      handleCanvasClick(e) {
        console.log('点击了');
        if (this.canBiaoZhu) {
          // console.log('点击了文字2', this.canBiaoZhu)
        } else if (this.hoveredMarker) {
          console.log(
            '点击了文字 可以进行部位筛选操作哦~',
            this.hoveredMarker.bodyPartsId
          );
          this.$emit('djbwfn', this.hoveredMarker.bodyPartsId);
          // this.currentMarker = this.hoveredMarker;
          // this.currentText = this.currentMarker.text;
          // this.editingMarker = true;
          this.editPanelX = e.clientX; // 可以保留 clientX/y，用于显示面板
          this.editPanelY = e.clientY;
        }
      },
      createMarker(x, y) {
        if (this.canBiaoZhu) {
          this.addflag = true;
          this.currentMarker = { x, y, color: this.pointColor };
          this.draw();
        }
      },

      draw() {
        // 处理图片逻辑

        if (!this.img.complete || this.img.naturalWidth === 0) {
          return;
        }

        const canvas = this.canvas;
        const ctx = this.ctx;
        const img = this.img;

        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // // 计算缩放尺寸
        // const aspectRatio = this.img.naturalWidth / this.img.naturalHeight;
        // const canvasAspectRatio = canvas.width / canvas.height;

        // // 设置最大宽度和高度
        // const maxWidth = canvas.width * 0.9; // 画布宽度的90%
        // const maxHeight = canvas.height * 0.9; // 画布高度的90%

        // if (canvasAspectRatio > aspectRatio) {
        //   this.imgScales = Math.min(maxHeight / this.img.naturalHeight, 1);
        // } else {
        //   this.imgScales = Math.min(maxWidth / this.img.naturalWidth, 1);
        // }

        // const scaledWidth = this.img.naturalWidth * this.imgScales;
        // const scaledHeight = this.img.naturalHeight * this.imgScales;

        // Calculate scaled image dimensions
        const scaledWidth = this.imgWidth * this.imgScale;
        const scaledHeight = this.imgHeight * this.imgScale;

        // Calculate image offset on the canvas
        const xOffset = (canvas.width - scaledWidth) / 2;
        const yOffset = (canvas.height - scaledHeight) / 2;

        // Draw the image
        ctx.drawImage(img, xOffset, yOffset, scaledWidth, scaledHeight);
        this.permarkers.forEach((item) => {
          if (item.dcomid == this.dcomid) {
            item.bsdata.forEach((marker) => {
              const markerX = marker.x * this.imgScale + xOffset;
              const markerY = marker.y * this.imgScale + yOffset;

              const isMarkerLeft = markerX < (canvas.width - 50) / 2 + 50 / 2;
              const lineLength = 100 * this.imgScale;
              const lineEndX = isMarkerLeft
                ? markerX - lineLength
                : markerX + lineLength;
              const lineEndY = markerY;

              const isHovered = marker == this.hoveredMarker;

              ctx.fillStyle = isHovered ? 'red' : marker.color;

              ctx.beginPath();
              ctx.arc(markerX, markerY, this.pointSize / 2, 0, 2 * Math.PI);
              ctx.fill();
            });
          }
        });
      },
      // 保存标记到本地缓存
      saveMarkers() {
        localStorage.setItem('permarkers', JSON.stringify([]));
        localStorage.setItem('permarkers', JSON.stringify(this.permarkers));
        this.draw();
        // if (this.permarkers) {
        //
        // }
      },
      // 加载本地缓存的标记
      loadMarkers() {
        // this.$emit('permarkersfn', []);
        const cachedMarkers = localStorage.getItem('permarkers');

        if (cachedMarkers) {
          // this.permarkers =JSON.parse(cachedMarkers)
          // this.$emit('permarkersfn', JSON.parse(cachedMarkers));
          this.draw();
        }
      },
      // 清除本地缓存
      clearCache() {
        localStorage.removeItem('permarkers');
        // this.permarkers = [];
        this.$emit('permarkersfn', []);
        this.draw();
      },
      // 切换显示旗标和文本
      //   toggleLinesAndText() {
      //     this.showLinesAndText = !this.showLinesAndText;
      //     this.draw();
      //   },
    },
    mounted() {
      this.hbheight = this.$refs.box.offsetHeight;
      this.hbwidth = this.$refs.box.offsetWidth;
      this.canvas = document.getElementById('myCanvas');
      this.ctx = this.canvas.getContext('2d');
      this.img = new Image();
      // console.log('加载一下图片', ())

      this.imgsrc = [
        {
          id: 1,
          src: './r.png',
        },
      ];

      this.img.src = this.imgsrc[0].src;
      this.img.onload = () => {
        this.loadMarkers();
        this.draw();
        // this.imgWidth = this.img.width;
        // this.imgHeight = this.img.height;
      };

      // 事件绑定
      this.canvas.onmousemove = (e) => this.handleMouseMove(e);
      this.canvas.addEventListener('click', (e) => this.handleCanvasClick(e));
      // 添加滚轮事件监听器
    },

    beforeDestroy() {
      // 事件解绑
      this.canvas.removeEventListener('mousemove', this.handleMouseMove);
      this.canvas.removeEventListener('click', this.handleCanvasClick);
    },
  };
</script>

<style scoped>
  #myCanvas {
    /* border: solid 1px #00ff80; */
    /* background-color: red; */
  }

  .edit-panel {
    position: absolute;
    background-color: white;
    border: 1px solid #ddd;

    padding: 10px;
    border-radius: 4px;
  }
  .box {
    margin: 20px auto;
    /* background-color: #00ff80; */
    width: 385px;
    height: 620px;
  }
  .bwiii {
    margin: 0 auto;
    color: #fff;
    text-align: center;
  }
</style>
